﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Configuration;

namespace Tools.SqlServer
{
    public class SqlTranHelper
    {

        //供GC调用的析构函数
        //~SqlTranHelper()
        //{
        //    EndTransaction();
        //}
        public SqlConnection _connection;
        public SqlTransaction _transaction;

        //public  string GetConnSting()
        //{
        //    return ConfigOperator.ConnectionStringConfig.GetValue("connectionString");
        //}

        //public  SqlConnection GetConnection()
        //{
        //    _connection = new SqlConnection(SqlHelper.GetConnSting());
        //    return _connection;
        //}

        public SqlTransaction BeginTransaction()
        {
            _connection = SqlHelper.GetConnection();
            if (_connection.State != ConnectionState.Open)
            {
                _connection.Open();
            }
            _transaction = _connection.BeginTransaction();
            return _transaction;
        }

        public void CommitTransaction()
        {
            if (_transaction != null)
            {

                _transaction.Commit();
            }
        }
        public void RollBackTransaction()
        {
            if (_transaction != null)
            {

                _transaction.Rollback();
            }
        }

        public void EndTransaction()
        {
            try
            {
                if (_transaction != null)
                {
                    _transaction.Dispose();
                    _transaction = null;
                }
                CloseConnection();
            }
            catch { }
        }

        public void CloseConnection()
        {
            if (_connection != null)
            {

                if (_connection.State != ConnectionState.Closed)
                {
                    _connection.Close();
                }
                _connection.Dispose();
                _connection = null;


            }
        }

        public SqlTransaction Trans
        {
            get { return _transaction; }
        }



    }
}
